# -*- coding: utf-8 -*-
# @Time    : 2024/1/7 22:12
# @Author  : micah
# @File    : 7.课外知识-b站视频下载.py
# @Software: PyCharm

import re
import requests
from bs4 import BeautifulSoup

url = 'https://www.bilibili.com/video/BV1aa4y127Co/?spm_id_from=333.1007.tianma.1-1-1.click'

headers = {
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36'
}

response = requests.get(url, headers=headers).text
soup = BeautifulSoup(response, 'lxml')

data = soup.find_all('script')[3]

video_url = re.search(r'"baseUrl":"(.*?)",', str(data)).group(1)
response = requests.get(video_url).content
with open('b站视频.mp4', mode='wb') as f:
    f.write(response)
